<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/17
 * Time: 17:20
 */

namespace app\index\controller;

use LaneWeChat\Core\WeChatOAuth;
use LaneWeChat\Core\UserManage;
use org\UUID;
use think\Cache;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Session;


class User extends Controller
{

    protected $token;

    public function _initialize()
    {


        $wx_config = Cache::get('wx_config');
        $user_info = Session::get('user_info');

        $this->token = Cache::has('access_token');
        if ($user_info) {
            $this->redirect('index/index/index');
        }


        define("WECHAT_APPID", $wx_config['appid']);
        define("WECHAT_APPSECRET", $wx_config['appsecret']);
        define("WECHAT_URL", (is_ssl() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . '/');


        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    public function index($invite_code = 0)
    {

        //公众号的唯一标识
        $appid = WECHAT_APPID;
        //授权后重定向的回调链接地址，请使用urlencode对链接进行处理
        $redirect_uri = WECHAT_URL . url('index/user/callback');
        $redirect_uri = urlencode($redirect_uri);
        //返回类型，请填写code
        $response_type = 'code';
        //构造请求微信接口的URL
        $scope = 'snsapi_userinfo';
        $state = "invite_code:{$invite_code}";
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . $redirect_uri . '&response_type=' . $response_type . '&scope=' . $scope . '&state='.$state.'#wechat_redirect';

        header('Location: ' . $url, true, 301);
    }

    public function callback()
    {

        $invite_code= 0;
        $state = $_GET['state'];
        $explode = explode(':',$state);
        if ($explode[1] !== 0){
            $invite_code = $explode[1];
        }

        $code = $this->request->get('code');
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . WECHAT_APPID . '&secret=' . WECHAT_APPSECRET . '&code=' . $code . '&grant_type=authorization_code';
        $res = request_curl($url);
        $res_data = json_decode($res, true);
        $access_token = $res_data['access_token'];
        $open_id = $res_data['openid'];
        $get_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $open_id . '&lang=zh_CN';

        $result = request_curl($get_info_url);
        $user_info = json_decode($result, true);


        if (!isset($user_info['openid'])) {
            $this->error('获取信息失败');
        }


        if (isset($user_info['openid'])) {

            $user_infos = Db::name('user')->where(['open_id' => $user_info['openid']])->find();
            if (!empty($user_infos)) {
                $token = [
                    'user_id' => $user_infos['id'],
                    'user_name' => $user_infos['username'],
                    'user_uuid' => $user_infos['user_uuid'],
                    'token' => md5($user_infos['username'] . time()),
                    'openid' => $user_infos['open_id'],
                    'login_time' => time(),
                    'client_type' => 'wap'
                ];


                Db::name('mb_user_token')->insert($token);

                $user_info_sess = [
                    'user_id' => $user_infos['id'],
                    'user_name' => $user_infos['username'],
                    'user_nick' => $user_infos['user_nick'],
                    'user_uuid' => $user_infos['user_uuid'],
                    'user_openid' => $user_infos['open_id'],
                    'user_token' => $token['token']
                ];
                $update = [
                    'last_login_time' => date('Y-m-d H:i:s'),
                    'last_login_ip' => $this->request->ip()
                ];
                if (empty($user_infos['headimg'])) {
                    $update['headimg'] = $user_info['headimgurl'];
                }
                Session::set('user_info', $user_info_sess);

                Db::name('user')->where(['id' => $user_infos['id']])->update($update);

            } else {
                //$inviter_code = Cookie::get('invite_code');
                if(isset($invite_code) && $invite_code != 0){
                    $invite_code = $invite_code;
                }
                //获取上级用户信息
                $inviter_info = Db::name('user')->where('user_uuid', $invite_code)->find();
                $inviter_id = 0;
                if (!empty($inviter_info)) {
                    $inviter_id = $inviter_info['id'];
                }
                $insert_info = [
                    'username' => md5($user_info['nickname'] . time()),
                    'password' => md5($user_info['openid'] . $user_info['nickname']),
                    'user_nick' => $user_info['nickname'],
                    'user_uuid' => UUID::v4(),
                    'open_id' => $user_info['openid'],
                    'create_time' => date('Y-m-d H:i:s'),
                    'coin' => 0,
                    'inviter_id' => $inviter_id,
                    'last_login_time' => date('Y-m-d H:i:s'),
                    'last_login_ip' => $this->request->ip(),
                    'headimg' => $user_info['headimgurl'],
                    'status' => 1

                ];

                $user_id = Db::name('user')->insertGetId($insert_info);

                $token = [
                    'user_id' => $user_id,
                    'user_name' => $insert_info['username'],
                    'user_uuid' => $insert_info['user_uuid'],
                    'token' => md5($insert_info['username'] . time()),
                    'openid' => $insert_info['open_id'],
                    'login_time' => time(),
                    'client_type' => 'wap'
                ];

                Db::name('mb_user_token')->insert($token);

                $user_info_sess = [
                    'user_id' => $user_id,
                    'user_name' => $insert_info['username'],
                    'user_nick' => $insert_info['user_nick'],
                    'user_uuid' => $insert_info['user_uuid'],
                    'user_openid' => $insert_info['open_id'],
                    'user_token' => $token['token']
                ];

                Session::set('user_info', $user_info_sess);
            }

            $this->redirect('index/index/index');
        }

    }

}